App.controller('routeStatController', ['$rootScope', '$scope', '$state', 'Page', 'XCode','$compile', function($rootScope, $scope, $state, Page, Xode, $compile) {

    $scope.isMapShow = false;
    $scope.routeStat = {};
    $scope.routes = {};
    $scope.displayedMarkers = [];

    //地图初始化
    $scope.init = function (id) {

        var map = new AMap.Map(id, {
            resizeEnable : true,
            zoom : 12,
            zooms : [4, 18]
        });

        //加载工具条
        map.plugin(['AMap.ToolBar'], function() {
            var toolBar = new AMap.ToolBar();
            map.addControl(toolBar);
        });

        //加载鹰眼
        map.plugin(["AMap.OverView"], function() {
            var view = new AMap.OverView();
            map.openOverView = function() {
                view.open();
            }
            map.addControl(view);
        });

        map.plugin(["AMap.Geocoder"], function() {
            var geocoder = new AMap.Geocoder({
                radius : 1000,
                extensions : "all"
            });
            map.geoQuery = function(points, callback, errorback, parms) {
                geocoder.getAddress(points, function(status, geoResult) {
                    if (status == 'complete' && geoResult.info === 'OK') {
                        if (callback) {
                            callback(status, geoResult, parms);
                        }
                    } else {
                        if (errorback) {
                            errorback(parms);
                        }
                    }
                });
            }
        });

        //加载定位插件
        map.plugin('AMap.Geolocation', function () {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true, //是否使用高精度定位，默认:true
                timeout: 10000,           //超过10秒后停止定位，默认：无穷大
                maximumAge: 0,            //定位结果缓存0毫秒，默认：0
                convert: true,            //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: false,        //显示定位按钮，默认：true
                showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
                showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
                zoomToAccuracy:false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            });

            map.addControl(geolocation);

            //geolocation.getCurrentPosition(); //精准定位
            //geolocation.getCityInfo();        //定位到城市

            AMap.event.addListener(geolocation, 'complete', function (_point) {
                Page.notice('定位成功：经度' + _point.position.getLng() + '; 维度：' + _point.position.getLat());
            });
            AMap.event.addListener(geolocation, 'error', function (_point) {
                Page.notice('定位失败');
            });
        });

        //初始中心点
        $scope.center = map.getCenter();

        return map;

    }

    $scope.map = $scope.init('map');

    //初始化线路
    Page.ajaxPost('routeStat/queryByRoute.do', {}, function(resp) {
        $scope.routes = resp.data;
        $scope.showRoute();
    });

    //显示线路
    $scope.showRoute = function () {

        // 删除历史marker和polyline
        $scope.map.remove($scope.displayedMarkers);
        $($scope.map.getAllOverlays('polyline')).each(function (i , _polyline) {
            $scope.map.remove(_polyline);
        })
        $scope.displayedMarkers = [];
        $scope.map.clearInfoWindow();
        //

        for(i = 0 ; i < $scope.routes.length ; i++){

            //显示起点
            var markerStart = new AMap.Marker({
                icon: 'assets/admin/img/mark_start.png',
                position: [$scope.routes[i].startStopLng, $scope.routes[i].startStopLat],
                extData: {
                    'startStopId':$scope.routes[i].startStopId,
                    'startStopName':$scope.routes[i].startStopName,
                    'startStopLng':$scope.routes[i].startStopLng,
                    'startStopLat':$scope.routes[i].startStopLat,
                    'endStopId':$scope.routes[i].endStopId,
                    'endStopName':$scope.routes[i].endStopName,
                    'endStopLng':$scope.routes[i].endStopLng,
                    'endStopLat':$scope.routes[i].endStopLat,
                    'num' : $scope.routes[i].num
                }
            });
            // markerStart.setzIndex(200);
            markerStart.setMap($scope.map);

            markerStart.setTitle($scope.routes[i].startStopName);

            //设置标签
            /*markerStart.setLabel({
                offset: new AMap.Pixel(8, 30),
                content: $scope.routes[i].startStopName
            });*/

            $scope.displayedMarkers.push(markerStart);

            //显示终点
            var markerEnd = new AMap.Marker({
                icon: 'assets/admin/img/mark_end.png',
                position: [$scope.routes[i].endStopLng, $scope.routes[i].endStopLat],
                extData: {
                    'startStopId':$scope.routes[i].startStopId,
                    'startStopName':$scope.routes[i].startStopName,
                    'startStopLng':$scope.routes[i].startStopLng,
                    'startStopLat':$scope.routes[i].startStopLat,
                    'endStopId':$scope.routes[i].endStopId,
                    'endStopName':$scope.routes[i].endStopName,
                    'endStopLng':$scope.routes[i].endStopLng,
                    'endStopLat':$scope.routes[i].endStopLat,
                    'num' : $scope.routes[i].num
                }
            });
            // markerEnd.setzIndex(200);
            markerEnd.setMap($scope.map);

            markerEnd.setTitle($scope.routes[i].endStopName);

            //设置标签
            /*markerEnd.setLabel({
                offset: new AMap.Pixel(8, 30),
                content: $scope.routes[i].endStopName
            });*/

            $scope.displayedMarkers.push(markerEnd);

            //根据统计线路条数显示不同宽度连线
            var weight = 1;
            var num = $scope.routes[i].num;
            switch(true){
                case num > 0 && num < 100:
                    weight = 2;
                    break;
                case num >= 100 && num < 200:
                    weight = 4;
                    break;
                case num >= 200 && num < 300:
                    weight = 6;
                    break;
                case num >= 300 && num < 400:
                    weight = 8;
                    break;
                case num >= 400 :
                    weight = 10;
                    break;
            }

            var lineArr = [
                [$scope.routes[i].startStopLng, $scope.routes[i].startStopLat],
                [$scope.routes[i].endStopLng, $scope.routes[i].endStopLat]
            ];
            var polyline = new AMap.Polyline({
                path: lineArr,          //设置线覆盖物路径
                strokeColor: "#FF3030", //线颜色
                strokeOpacity: 0.9,       //线透明度
                strokeWeight: weight,        //线宽
                strokeStyle: "solid",   //线样式
                showDir: true,
                strokeDasharray: [10, 5] //补充线样式
            });
            polyline.setMap($scope.map);

        }

        // 信息弹框
        $($scope.displayedMarkers).each(function (i, _marker) {

            _marker.on('click', function (e) {

                var html = '<div>' +
                    '<div>'+
                    '<div class="info" style="border: solid 1px silver;">'+
                    '   <div class="info-top" style="position: relative;background: none repeat scroll 0 0 #F9F9F9;border-bottom: 1px solid #CCC;border-radius: 5px 5px 0 0;">' +
                    '       <div style="display: inline-block; color: #333333;font-size: 14px; font-weight: bold;line-height: 31px;padding: 0 10px;">详情</div>' +
                    '       <img style="position: absolute;top: 10px;right: 10px;transition-duration: 0.25s;" src="http://webapi.amap.com/images/close2.gif" ng-click="map.clearInfoWindow()">' +
                    '   </div>' +
                    '   <div class="info-middle" style="background-color: white; font-size: 12px;padding: 6px;line-height: 20px;">' +
                    '       <label>起点：</label>' + _marker.getExtData().startStopName + '<br/>' +
                    '       <label>终点：</label>' + _marker.getExtData().endStopName + '<br/>' +
                    '       <label>热度：</label>' + _marker.getExtData().num +
                    '   </div>' +
                    '   <div class="info-bottom" style="height: 0px;width: 100%;clear: both;text-align: center;">' +
                    '       <img style="position: relative; z-index: 104;" src="http://webapi.amap.com/images/sharp.png">' +
                    '   </div>'+
                    '</div>' +
                    '</div>' +
                    '</div>';


                var template = angular.element(html);

                //编译模板
                var Element = $compile(template)($scope);

                infoWindow = new AMap.InfoWindow({
                    isCustom: true,
                    offset: new AMap.Pixel(15, -50),
                    content: Element[0]
                });

                infoWindow.open($scope.map, e.target.getPosition());

            });

            //注册鼠标移入事件
            /*_marker.on('mouseover', function(e) {
                _marker.setLabel({
                    offset: new AMap.Pixel(8, 30),
                    content: '1111'
                });
            });

            _marker.on('mouseout', function(e) {
                _marker.setLabel({
                    offset: new AMap.Pixel(8, 30),
                    content: '22222'
                });
            });*/

        });
    } ;

    //切换数据与热图
    $scope.toogleMap = function () {
        $scope.isMapShow = $scope.isMapShow ? false : true ;
    }

    //自定义查询
    $scope.query = function () {
        if($scope.isMapShow){
            Page.ajaxPost('routeStat/queryByRoute.do', $scope.routeStat, function(resp) {
                $scope.routes = resp.data;
                $scope.showRoute();
            });
        }else{
            $scope.grid.query();
        }
    }

    //自定义重置
    $scope.reset = function () {
        $scope.routeStat = {};
        if($scope.isMapShow){
            Page.ajaxPost('routeStat/queryByRoute.do', {}, function(resp) {
                $scope.routes = resp.data;
                $scope.showRoute();
            });
        }else{
            $scope.grid.reset();
        }
    }

}]);